<template>
  <div class="spare-picker-plus">
    <!-- 选择区：左短右按钮 -->
    <el-form-item label="从备件库选择">
      <div class="select-row">
        <el-select
          v-model="pickedIds"
          multiple
          filterable
          clearable
          collapse-tags
          collapse-tags-tooltip
          :placeholder="placeholder"
          :style="{ width: selectWidth }"
          @change="syncPickedToRows"
        >
          <el-option
            v-for="op in allOptions"
            :key="op.value"
            :label="`(${typeLabel(op.type)}) ${op.label}`"
            :value="op.value"
          />
        </el-select>

        <el-button type="primary" plain class="ml8" @click="openAddDialog">
          新增备件
        </el-button>
      </div>
    </el-form-item>

    <!-- 工具栏 -->
    <!-- <div class="toolbar">
      <el-button type="primary" plain @click="addManualRow">手动新增一行</el-button>
      <el-text type="info" class="tip">
        编码仅允许 A-Z / 0-9 / - / _；手动新增如不存在将以 code 新建。
      </el-text>
    </div> -->

    <!-- 明细表 -->
    <el-table
      :data="rows"
      border
      stripe
      size="small"
      :height="tableHeight"
      empty-text="请通过上方选择已有备件"
    >
      <el-table-column label="备件名称" min-width="100">
        <template #default="{ row }">
          <el-input
            v-model="row.name"
            placeholder="请输入备件名称"
            @change="emitRows"
            :disabled="isLibRow(row)"
          />
        </template>
      </el-table-column>

      <!-- <el-table-column label="编码" min-width="120" >
          <template #default="{ row }">
            <el-input
              v-model="row.code"
              maxlength="64"
              placeholder="仅字母/数字/-/_"
              @input="row.code = sanitizeCode(row.code)"
              @change="emitRows"
              :disabled="isLibRow(row)"
            />
          </template>
        </el-table-column>  -->
        
        <el-table-column label="备件类型" min-width="80" align="center">
          <template #default="{ row }">
            <el-select v-model="row.type" style="width:100%" :disabled="isLibRow(row)">
              <el-option :value="0" label="普通"/>
              <el-option :value="1" label="特殊"/>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="所需数量" min-width="80" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.qty"
            :min="1"
            :step="1"
            controls-position="right"
            @change="emitRows"
          />
        </template>
      </el-table-column>

      <!-- <el-table-column label="所需数量" width="120" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.qty"
            :min="1"
            :step="1"
            controls-position="right"
            @change="onQtyChange(row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="当前库存" width="120" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.stockAvailable"
            :min="1"
            :step="1"
            controls-position="right"
            @change="emitRows"
          />
        </template>
      </el-table-column> -->

      <el-table-column label="采购周期(天)" min-width="100" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.orderDate"
            :min="0"
            :step="1"
            controls-position="right"
            @change="emitRows"
          />
        </template>
      </el-table-column>

      <!-- <el-table-column label="计划工时" width="120" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.planHour"
            :min="1"
            :step="1"
            controls-position="right"
            @change="onQtyChange(row)"
          />
        </template>
      </el-table-column> -->

      <el-table-column label="操作" min-width="50" align="center" fixed="right">
        <template #default="{ $index }">
          <!-- <el-button link type="primary" size="small" @click="copyRow($index)">复制</el-button> -->
          <el-button link type="danger" size="small" @click="removeRow($index)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 备件新增弹窗（沿用你已有的 SpareFormDialog） -->
    <SpareFormDialog
      v-model:visible="dlgVisible"
      :mode="dlgMode"
      :model="dlgModel"
      :submitting="dlgLoading"
      @submit="onDlgSubmit"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import { listSpare, addSpare, updateSpare } from "@/api/sbtz/spare";
import SpareFormDialog from "@/components/sbtz/spare/SpareFormDialog.vue";
import { ElMessageBox } from "element-plus";

/**
 * v-model:specialItems 统一对外结构（与后端 payload 对齐）：
 * { spareId?, code, name, type, qty, orderDate, assetId? }
 */
const props = defineProps({
  specialItems: { type: Array, default: () => [] },
  tableHeight: { type: [Number, String], default: 200 },
  // 选择框宽度（缩短）
  selectWidth: { type: String, default: "420px" },
  placeholder: {
    type: String,
    default: "选择需要的备件（可多选，含普通与特殊）",
  },
  // 新增成功后，是否默认把 type 置为特殊（通常由表单控制，这里保持 false）
  forceNewTypeSpecial: { type: Boolean, default: false },
});
const emit = defineEmits(["update:specialItems"]);

/* ---------- 状态 ---------- */
const allOptions = ref([]); // 备件库（id/name/code/type/orderDate）
const pickedIds = ref([]); // 下拉选中
const rows = ref([]); // 编辑表格行

const typeLabel = (t) => (Number(t) === 1 ? "特殊" : "普通");
const sanitizeCode = (s = "") => s.toUpperCase().replace(/[^A-Z0-9\-_]/g, "");
const isLibRow = (row) => !!row?.spareId;

function emitRows() { 
  emit("update:specialItems", rows.value);
}

function onQtyChange(row) {
  // 仅当有“当前库存”数值时校验（手动新增行可能没有这个字段）
  const hasStock =
    row.stockAvailable !== undefined && row.stockAvailable !== null;
  const avail = Number(row.stockAvailable);
  const qty = Number(row.qty);

  if (hasStock && Number.isFinite(avail) && qty > avail) {
    // 重置为 1 并弹窗提示
    row.qty = 1;
    ElMessageBox.alert("所需数量不能大于当前库存", "提示", { type: "warning" });
  }
  emitRows();
}

/* ---------- 初始化 ---------- */
onMounted(async () => {
  await reloadOptions();
  // 回显
  if (Array.isArray(props.specialItems) && props.specialItems.length) {
    rows.value = props.specialItems.map((x) => ({
      spareId: x.spareId, // 可能为空
      code: sanitizeCode(x.code),
      name: x.name || "",
      type: Number(x.type) || 0,
      qty: Number(x.qty) || 1,
      planHour: Number(x.planHour) || 10,
      orderDate: Number(x.orderDate || 0),
      assetId: x.assetId,
      stockAvailable: Number(x.stockAvailable ?? 0),
    }));
    pickedIds.value = rows.value.filter((r) => r.spareId).map((r) => r.spareId);
  }
});

watch(
  () => props.specialItems,
  (v) => {
    if (Array.isArray(v)) {
      rows.value = v.map((x) => ({
        spareId: x.spareId,
        code: sanitizeCode(x.code),
        name: x.name || "",
        type: Number(x.type) || 0,
        qty: Number(x.qty) || 1,
        planHour: Number(x.planHour) || 10,
        orderDate: Number(x.orderDate || 0),
        assetId: x.assetId,
        stockAvailable: Number(x.stockAvailable ?? 0),
      }));
      pickedIds.value = rows.value
        .filter((r) => r.spareId)
        .map((r) => r.spareId);
    }
  },
  { deep: true }
);

/* ---------- API ---------- */
async function reloadOptions() {
  const res = await listSpare({ pageNum: 1, pageSize: 9999 });
  const list = res?.rows ?? res?.data ?? [];

  allOptions.value = list.map((r) => ({
    value: r.id,
    label: r.name,
    code: (r.code || "").toUpperCase(),
    type: Number(r.type) || 0,
    planHour: Number(r.planHour) || 10,
    orderDate: Number(r.order_date ?? r.orderDate ?? 0),
    stockAvailable: Number(r.stockAvailable ?? r.stockAvailable ?? 0),
  }));
}

/* ---------- 选择同步 ---------- */
function syncPickedToRows() {
  const picked = new Set(pickedIds.value);
  // 保留仍选中的库内行 & 手动行不受影响
  rows.value = rows.value.filter((r) => !r.spareId || picked.has(r.spareId));

  // 把新选的库内项追加到表格
  for (const id of picked) {
    if (!rows.value.some((r) => r.spareId === id)) {
      const op = allOptions.value.find((x) => x.value === id);
      if (op) {
        rows.value.push({
          spareId: id,
          code: op.code,
          name: op.label,
          type: Number(op.type) || 0,
          qty: 1,
          planHour: 10,
          orderDate: Number(op.orderDate || 30),
          stockAvailable: Number(op.stockAvailable || 0),
        });
      }
    }
  }
  emitRows();
}

/* ---------- 行操作 ---------- */
function addManualRow() {
  rows.value.push({
    code: "",
    name: "",
    type: 1,
    qty: 1,
    planHour: 10,
    orderDate: 0,
    stockAvailable: 0,
  });
  emitRows();
}

function copyRow(i) {
  const src = rows.value[i];
  const dup = JSON.parse(JSON.stringify(src));
  // 库内行复制 → 保留 spareId；手动行复制 → 清除 spareId
  dup.spareId = isLibRow(src) ? src.spareId : undefined;
  rows.value.splice(i + 1, 0, dup);
  emitRows();
}

function removeRow(i) {
  const removed = rows.value[i];
  rows.value.splice(i, 1);
  if (removed?.spareId) {
    pickedIds.value = pickedIds.value.filter((id) => id !== removed.spareId);
  }
  emitRows();
}

/* ---------- 新增备件弹窗 ---------- */
const dlgVisible = ref(false);
const dlgMode = ref("add"); // 'add' | 'edit'（目前主要用新增）
const dlgLoading = ref(false);
const dlgModel = ref({});

function openAddDialog() {
  dlgMode.value = "add";
  dlgModel.value = {
    unit: "个",
    status: 0,
    type: 0,
    stockTotal: 0,
    stockAvailable: 0,
    variants: [],
  };
  dlgVisible.value = true;
}

async function onDlgSubmit(payload) {
  dlgLoading.value = true;
  try {
    if (dlgMode.value === "add") {
      const res = await addSpare(payload);
      // 后端返回新增 id
      const newId = res?.data?.id ?? res?.id;
      // 刷新备件库
      await reloadOptions();

      // 自动选中并加入当前表格
      const op = allOptions.value.find((x) => x.value === newId);
      if (op) {
        // 下拉选中
        if (!pickedIds.value.includes(newId)) pickedIds.value.push(newId);
        // 表格追加
        rows.value.push({
          spareId: newId,
          code: op.code,
          name: op.label,
          type: props.forceNewTypeSpecial ? 1 : Number(op.type) || 0,
          qty: 1,
          orderDate: Number(op.orderDate || 0),
          stockAvailable: Number(op.stockAvailable ?? 0),
        });
        emitRows();
      }
      // 关闭弹窗
      dlgVisible.value = false;
    } else {
      await updateSpare(payload);
      await reloadOptions();
      dlgVisible.value = false;
    }
  } finally {
    dlgLoading.value = false;
  }
}
</script>

<style scoped>
.spare-picker-plus {
}
.select-row {
  display: flex;
  align-items: center;
  gap: 8px;
}
.ml8 {
  margin-left: 8px;
}
.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 8px 0 12px 0;
}
.tip {
  font-size: 12px;
}
</style>
